/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-06-11
*/
package com.rzico.basics.controller;

import com.alibaba.fastjson.JSON;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.amap.AmapUtils;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.MapLine;
import com.rzico.basics.entity.Member;
import com.rzico.basics.entity.Shop;
import com.rzico.basics.model.MapPoint;
import com.rzico.basics.model.ShopVo;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.MapLineService;
import com.rzico.basics.service.MemberService;
import com.rzico.basics.service.ShopService;
import com.rzico.core.entity.SysMch;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.SysMchService;
import com.rzico.core.service.SysUserService;
import com.rzico.util.IPUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定位接口
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-06-11
 */
@Api(description = "定位接口")
@RestController
@RequestMapping("/amap")
public class AMapController extends BaseController {

    @Autowired
    private AmapUtils amapUtils;

    @Autowired @Lazy
    private EnterpriseService enterpriseService;

    @Autowired @Lazy
    private ShopService shopService;

    @Autowired @Lazy
    private MapLineService mapLineService;

    @Autowired @Lazy
    private SysMchService sysMchService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 批量标记为已读
     *
     * @param request
     * @return
     */
    @Log(desc = "通用客户端IP获取当前城市", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("通用客户端IP获取当前城市")
    @PostMapping("/IPLocation")
    public CommResult<Map> IPLocation(HttpServletRequest request) {
        String ip = IPUtils.getIp(request);
        Map<String,Object> data = amapUtils.IPLocation(ip);

        return CommResult.success(data);
    }

    /**
     * 按位置获取周边设施
     *
     * @param request
     * @return
     */
    @Log(desc = "按位置获取周边设施", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("按位置获取周边设施")
    @PostMapping("/POILocation")
    public CommResult<Map> POILocation(Double lat,Double lng,HttpServletRequest request) {
        Map<String,Object> data = amapUtils.geoPois(lat,lng);
        return CommResult.success(data);
    }


    /**
     * 关键词搜索周边设置
     *
     * @param request
     * @return
     */
    @Log(desc = "关键词搜索周边设置", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("关键词搜索周边设置")
    @PostMapping("/POIQuery")
    public CommResult<Map> POIQuery(String keyword,Double lat,Double lng,HttpServletRequest request) {
        Map<String,Object> data = amapUtils.geoPoisQuery(keyword,lat,lng);
        return CommResult.success(data);
    }


    /**
     * 批量标记为已读
     *
     * @param request
     * @return
     */
    @Log(desc = "通用客户端IP获取当前城市", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("通用客户端IP获取当前城市")
    @PostMapping("/LBSLocation")
    public CommResult<Map> LBSLocation(Double lat,Double lng,HttpServletRequest request) {
        Map<String,Object> data = amapUtils.geoCode(lat,lng);
        return CommResult.success(data);
    }

    /**
     * 按用户当前位置获取最近商户
     *
     * @return
     */
    @Log(desc = "按用户当前位置获取最近商户", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("按用户当前位置获取最近商户")
    @PostMapping("/MCHLocation")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "isvId",  value = "服务端", dataType = "String", paramType = "query")
    })
    public CommResult<Map> MCHLocation(String isvId,Double lat,Double lng) {

        if (lat==null) {
            return CommResult.error("请开启定位功能");
        }
        if (lng==null) {
            return CommResult.error("请开启定位功能");
        }

        Enterprise enterprise = enterpriseService.findByMch(isvId);

        Shop shop = null;

        //送货线路优先，没有时分配最近的门店
        MapLine mapLine = mapLineService.findByISV(enterprise,lat,lng);
        if (mapLine!=null) {
            shop = shopService.findById(mapLine.getShopId());
/*  全按送货线路来
        } else {
            shop = shopService.findByISV(enterprise, lat, lng);
*/
        }
        if (shop==null) {
            //没有特约商户时分配给总店，由总店再支配
            mapLine = mapLineService.findByPoint(enterprise,null,lat,lng);
            if (mapLine!=null) {
                shop = shopService.findById(mapLine.getShopId());
            } else {
               // shop = shopService.findByPoint(enterprise, lat, lng);
            }
        }

        if (shop==null) {
            return CommResult.success("超出配送范围");
        }

        Enterprise she = enterpriseService.findById(shop.getEnterpriseId());

        SysMch sysMch = sysMchService.findById(she.getMchId());

        Map<String,Object> data = new HashMap<>();
        data.put("sysMch",sysMch);
        ShopVo vo = new ShopVo();
        vo.setId(shop.getId());
        vo.setDistance(-1d);
        //在配送范围，判断离谁近
        if (shop.getLat()==null) {
            shop.setLat(0d);
        }
        if (shop.getLng()==null) {
            shop.setLng(0d);
        }
        if (shop.getLat()>0 && shop.getLat()>0) {
            MapPoint point = new MapPoint();
            point.setLat(lat);
            point.setLng(lng);

            MapPoint shopPoint = new MapPoint();
            shopPoint.setLat(shop.getLat());
            shopPoint.setLng(shop.getLng());
            vo.setDistance(point.distatce(shopPoint));
        }
        vo.setName(shop.getName());
        vo.setAddress(shop.getAddress());
        vo.setLinkman(shop.getLinkman());
        vo.setLogo(sysMch.getLogo());
        data.put("shop",vo);

        return CommResult.success(data);
    }


    @ApiOperation("获取归属的商户信息")
    @GetMapping(value = "/getMchInfo")
    public CommResult<Member> getMchInfo(String xuid,HttpServletRequest request) {

        Member member = memberService.getCurrent();
        Map<String, Object> data = new HashMap<>();
        SysMch sysMch = null;

        Shop shop = null;
        //如果有店铺，代表已锁定了

        if (xuid!=null) {
            //先获取推荐人商户
            SysUser sysUser = sysUserService.selectByPrimaryKey(xuid);
            if (sysUser == null) {
                return CommResult.error("无效推荐ID");
            }

            // 1.商家账号
            if (sysUser.getUserType().equals(1)) {
                sysMch = sysMchService.findById(sysUser.getMchId());
            } else {
                member = memberService.findByUserId(sysUser.getId());
                if (member!=null) {
                    Enterprise enterprise = enterpriseService.findById(member.getEnterpriseId());
                    sysMch = sysMchService.findById(enterprise.getMchId());
                }
            }
            if (sysMch!=null) {
                Enterprise en = enterpriseService.findByMch(sysMch.getId());
                shop = shopService.findByPoint(en, 0d, 0d);
            }
        }

        //如果是老会员
        if (member!=null){
            Enterprise enterprise = enterpriseService.findById(member.getEnterpriseId());
            SysMch userMch = sysMchService.findById(enterprise.getMchId());

            //有注册过，判断是不是总店会员，总店会员在没有消费情况可以被抢
            if (sysMch!= null && member!=null && member.getAmount().compareTo(BigDecimal.ZERO)==0 && member.getVip()==0) {
                if (member.getShopId()==null) {
                    userMch = sysMch;
                    member.setShopId(null);
                }
            }

            sysMch = userMch;
            if (member.getShopId()!=null) {
                shop = shopService.findById(member.getShopId());
            }
        }

        data.put("sysMch",sysMch);
        data.put("shop",null);
        if (sysMch!=null && shop!=null) {
            ShopVo vo = new ShopVo();
            vo.setId(shop.getId());
            vo.setDistance(-1d);
            vo.setName(shop.getName());
            vo.setAddress(shop.getAddress());
            vo.setLinkman(shop.getLinkman());
            vo.setLogo(sysMch.getLogo());
            data.put("shop",vo);
            data.put("locked",shop!=null);
        } else {
            data.put("locked",false);
        }

        return CommResult.success(data);
    }

}
